/**
 * 
 */
package com.geezdata.cps.sdk3rd.wechat.method;

import java.io.IOException;
import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.base.utils.JaxbUtil;
import com.geezdata.cps.sdk3rd.wechat.request.WechatHongbaoRecordRequest;
import com.geezdata.cps.sdk3rd.wechat.response.WechatHongbaoRecordResult;

/**
 * @author sszheng
 * @date 创建时间：2018年4月20日 下午3:37:37
 *
 */
public class WechatHongbaoRecord extends WechatPay implements Wechat<WechatHongbaoRecordRequest, WechatHongbaoRecordResult> {
	private static final Logger logger = LoggerFactory.getLogger(WechatHongbaoRecord.class);
	private static String HONGBAO_RECORD_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo";
	
	@Override
	public WechatHongbaoRecordResult execute(WechatHongbaoRecordRequest request) {
		SortedMap<String, Object> params = prepareParams(request);
		generateSign(params, request.getPayKey());
		String requestXML = convert2Xml(params);
		
		try {
			String rspStr = HttpClientUtil.post(HONGBAO_RECORD_URL, requestXML, HttpClientUtil.sslHttpClient(
					request.getKeyStorePath(), request.getKeyStorePassword(), request.getKeyStoreType()));
			logger.error(rspStr);
			if(rspStr.contains("xml")){
				String xmlRspStr = rspStr.replaceAll("\r|\n", "");
				WechatHongbaoRecordResult result= JaxbUtil.converyToJavaBean(xmlRspStr, WechatHongbaoRecordResult.class);
				return result;
			 }
		} catch (IOException e) {
			logger.error("WeixinHongbao::execute failed url {}, params {}", HONGBAO_RECORD_URL, requestXML);
		}
		
		return null;
	}

	private SortedMap<String, Object> prepareParams(WechatHongbaoRecordRequest request) {
		SortedMap<String, Object> params = new TreeMap<String, Object>();
        params.put("nonce_str", generateNonceStr());
        params.put("bill_type", "MCHT");
        params.put("mch_id", request.getMchId());  
        params.put("appid", request.getAppId()); 
        params.put("mch_billno", request.getBillNo());  
        return params;  
	}
}
